﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Linq;
using System.Globalization;

namespace QuanLyKTX
{
    using DAL;
    using Telerik.WinControls.UI;

    public partial class frm_IncomeBill : Telerik.WinControls.UI.RadForm
    {

        RadContextMenu radContextMenu;
        bool update = false;
        public int SoPhieuThu { get; set; }

        #region Private Methods

        private void InitLoadForm()
        {
            radDateTimePicker_NgayThu.Value = DateTime.Now;
            radDateTimePicker_NgayThu.Focus();

            radDropDownList_MucDichThu.ListElement.Font = new Font("Segoe UI", 14F, FontStyle.Regular, GraphicsUnit.Pixel);
            radDropDownList_KyThang.ListElement.Font = new Font("Segoe UI", 14F, FontStyle.Regular, GraphicsUnit.Pixel);
            radDropDownList_MucDichThu.ListElement.ItemHeight = 28;
            radDropDownList_KyThang.ListElement.ItemHeight = 28;

            // Init data to DropDowList Muc Dich Thu
            List<RadListDataItem> lItems = new List<RadListDataItem>();

            for (int i = 0; i <= 2; i++)
            {
                RadListDataItem mucDichThu = new RadListDataItem { Value = i };
                switch (i)
                {
                    case 0:
                        mucDichThu.Text = "Thu tiền đặt cọc";
                        break;
                    case 1:
                        mucDichThu.Text = "Thu tiền phòng";
                        break;
                    case 2:
                        mucDichThu.Text = "Thu tiền Điện - Nước";
                        break;
                }
                lItems.Add(mucDichThu);
            }

            radDropDownList_MucDichThu.Items.AddRange(lItems);
            radDropDownList_MucDichThu.Items[0].Selected = true; ;

            // Init data to DropDownList Ky thang
            lItems.Clear();
            for (int i = 1; i <= 12; i++)
            {
                RadListDataItem kyThang = new RadListDataItem { Value = i, Text = i.ToString() };

                lItems.Add(kyThang);
            }

            radDropDownList_KyThang.Items.AddRange(lItems);
            radDropDownList_KyThang.Text = DateTime.Now.Month.ToString();

            // Init Year
            radMaskedEditBox_Nam.Value = DateTime.Now.Year.ToString();

            BindGridPhieuThu();
        }

        private void ResetForm()
        {
            radTextBox_Ho.Clear();
            radTextBox_Ten.Clear();
            radTextBox_DiaChi.Clear();
            radTextBox_LyDoNop.Clear();
            radTextBox_MaSinhVien.Clear();

            radMaskedEditBox_SoCMND.Value = "";
            radMaskedEditBox_SoCMND.Text = "_________";
            radMaskedEditBox_SoTien.Value = 0;
            radMaskedEditBox_SoTien.Text = "0 ₫";
            radDateTimePicker_NgayThu.Focus();

            update = false;
        }

        private string MucDichThuDef(byte i)
        {
            switch (i)
            {
                case 0:
                    return "Thu tiền đặt cọc";
                case 1:
                    return "Thu tiền phòng";
                default:
                    return "Thu tiền Điện - Nước";
            }
        }

        private void BindGridPhieuThu()
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var results = from p in db.tbl_PhieuThus
                              orderby p.MaPhieuThu descending
                              select new
                              {
                                  p.MaPhieuThu,
                                  p.HauTo,
                                  p.IDSinhVien,
                                  p.MaSinhVien,
                                  p.SoCMND,
                                  p.HoTenNguoiNop,
                                  p.DiaChi,
                                  p.KyThang,
                                  p.Nam,
                                  p.LyDoNop,
                                  p.SoTien,
                                  p.NgayLapPhieu,
                                  MucDich = MucDichThuDef(Convert.ToByte(p.MucDichThu)),
                                  SoPhieuThu = string.Format("{0}/{1}", p.MaPhieuThu, p.HauTo)
                              };

                if (results.Count() > 0)
                {
                    radGridView_PhieuThu.DataSource = results;
                }
            }

        }

        private bool InsPhieuThu(DateTime ngayThu, byte mucDichThu, byte kyThang, string nam, int idSinhVien, string hoTen, string maSinhVien, string soCMND, string diaChi, string lyDoNop, decimal soTien)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                try
                {
                    tbl_PhieuThu phieuThu = new tbl_PhieuThu()
                    {
                        NgayLapPhieu = ngayThu,
                        MucDichThu = mucDichThu,
                        KyThang = kyThang,
                        Nam = nam,
                        IDSinhVien = idSinhVien,
                        HoTenNguoiNop = hoTen,
                        DiaChi = diaChi,
                        MaSinhVien = maSinhVien,
                        SoCMND = soCMND,
                        LyDoNop = lyDoNop,
                        HauTo = string.Format("VL/KTX/PT/{0}", ngayThu.Year),
                        SoTien = soTien
                    };

                    db.tbl_PhieuThus.InsertOnSubmit(phieuThu);
                    db.SubmitChanges();

                    BindGridPhieuThu();

                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return false;
        }

        private bool UpdPhieuThu(int maPhieuThu,byte mucDichThu, decimal soTien,string lyDoNop)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                try
                {
                    var phieuThu = (from p in db.tbl_PhieuThus
                                    where p.MaPhieuThu == maPhieuThu
                                    select p).FirstOrDefault();
                    phieuThu.LyDoNop = lyDoNop;
                    phieuThu.MucDichThu = mucDichThu;
                    phieuThu.SoTien = soTien;
                    db.SubmitChanges();
                    ResetForm();                    
                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return false;
                }
            }
        }

        private int GetIDSinhVien(string ho, string ten, string maSinhVien, string soCMND)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                if (!string.IsNullOrEmpty(maSinhVien))
                {
                    var result = (from p in db.tbl_SinhViens
                                  where p.MaSinhVien == maSinhVien
                                  select p.ID).FirstOrDefault();

                    if (result > 0) return result;
                }
                else
                {
                    if (!string.IsNullOrEmpty(soCMND))
                    {
                        var result = (from p in db.tbl_SinhViens
                                      where p.SoCMND == soCMND
                                      select p.ID).FirstOrDefault();

                        if (result > 0) return result;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(ho) && !string.IsNullOrEmpty(ten))
                        {
                            //var parten = new[] { " " };
                            //var name = hoTen.Split(parten, System.StringSplitOptions.RemoveEmptyEntries);
                            //var ho = string.Empty;
                            //for (int i = 0; i < name.Count() - 1; i++)
                            //{
                            //    ho = string.Format("{0} {1}", ho, name[i].Trim());
                            //}
                            //var ten = name[name.Count() - 1].Trim();

                            var result = (from p in db.tbl_SinhViens
                                          where p.Ho == ho && p.Ten == ten
                                          select p.ID).FirstOrDefault();

                            if (result > 0)
                            {
                                return result;
                            }
                        }
                    }
                }
            }
            return 0;
        }

        private void InitContextMenu()
        {
            radContextMenu = new RadContextMenu();

            RadMenuItem menuIn = new RadMenuItem("In");
            menuIn.Click += menuIn_Click;
            RadMenuItem menuSua = new RadMenuItem("Sửa");
            menuSua.Click += new EventHandler(menuSua_Click);

            radContextMenu.Items.Add(menuIn);
            radContextMenu.Items.Add(menuSua);
        }

        void menuSua_Click(object sender, EventArgs e)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var phieuThu = (from p in db.tbl_PhieuThus
                               where p.MaPhieuThu == Convert.ToInt32(radGridView_PhieuThu.CurrentRow.Cells[0].Value)
                                select p).FirstOrDefault() ;
                radDateTimePicker_NgayThu.Value = phieuThu.NgayLapPhieu.Value.Date;
                radDropDownList_MucDichThu.SelectedIndex = phieuThu.MucDichThu.Value;
                radDropDownList_KyThang.SelectedIndex = phieuThu.KyThang.Value - 1;
                radMaskedEditBox_Nam.Value = phieuThu.Nam;

                var parten = new[] { " " };
                var name = phieuThu.HoTenNguoiNop.Split(parten, System.StringSplitOptions.RemoveEmptyEntries);
                var ho = string.Empty;
                for (int i = 0; i < name.Count() - 1; i++)
                {
                    ho = string.Format("{0} {1}", ho, name[i].Trim());
                }
                var ten = name[name.Count() - 1].Trim();

                radTextBox_Ho.Text = ho;
                radTextBox_Ten.Text = ten;
                radTextBox_MaSinhVien.Text = phieuThu.MaSinhVien;
                radMaskedEditBox_SoCMND.Value = phieuThu.SoCMND;
                radTextBox_DiaChi.Text = phieuThu.DiaChi;
                radTextBox_LyDoNop.Text = phieuThu.LyDoNop;
                radMaskedEditBox_SoTien.Value = phieuThu.SoTien.Value.ToString("F0", CultureInfo.InvariantCulture);
                SoPhieuThu = phieuThu.MaPhieuThu;
                update = true;
            }
        }

        #endregion

        #region Events

        private void radGridView_PhieuThu_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
        {
            if (!radGridView_PhieuThu.CurrentRow.IsSystem)
            {
                e.ContextMenu = radContextMenu.DropDown;
            }
        }

        void menuIn_Click(object sender, EventArgs e)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var result = (from p in db.tbl_PhieuThus
                              where p.MaPhieuThu == Convert.ToInt32(radGridView_PhieuThu.CurrentRow.Cells[0].Value)
                              select p).FirstOrDefault();

                using (var frmReportIncomeBill = new frm_ReportIncomeBill(result.MaPhieuThu))
                {
                    frmReportIncomeBill.ShowDialog();
                }

            }


        }

        private void radButton_Huy_Click(object sender, EventArgs e)
        {
            ResetForm();
        }

        private void radButton_LuuVaIn_Click(object sender, EventArgs e)
        {
            DateTime ngayThu = radDateTimePicker_NgayThu.Value;
            byte mucDichThu = Convert.ToByte(radDropDownList_MucDichThu.SelectedValue);
            byte kyThang = Convert.ToByte(radDropDownList_KyThang.Text);
            string ho = radTextBox_Ho.Text.Trim();
            string ten = radTextBox_Ten.Text.Trim();
            string hoTen = string.Format("{0} {1}", ho, ten);
            string maSinhVien = radTextBox_MaSinhVien.Text.Trim();
            string soCMND = radMaskedEditBox_SoCMND.Value.ToString();
            string diaChi = radTextBox_DiaChi.Text.Trim();
            string lyDoNop = radTextBox_LyDoNop.Text.Trim();
            decimal soTien = Convert.ToDecimal(radMaskedEditBox_SoTien.Value);
            int idSinhVien = GetIDSinhVien(ho, ten, maSinhVien, soCMND);
            string nam = radMaskedEditBox_Nam.Value.ToString();

            if (!update)
            {
                if (!string.IsNullOrEmpty(ho) && !string.IsNullOrEmpty(ten))
                {
                    if (idSinhVien > 0)
                    {
                        using (var db = new QuanLyKTXDataContext())
                        {
                            var result = (from p in db.tbl_SinhViens
                                          where p.ID == idSinhVien
                                          select p).FirstOrDefault();
                            maSinhVien = result.MaSinhVien;
                            soCMND = result.SoCMND;

                            bool flag = InsPhieuThu(ngayThu, mucDichThu, kyThang, nam, idSinhVien, hoTen, maSinhVien, soCMND, diaChi, lyDoNop, soTien);
                            if (flag)
                            {
                                var maPhieuThu = (from p in db.tbl_PhieuThus
                                                  select p.MaPhieuThu).Max(r => r);
                                using (frm_ReportIncomeBill rptIncomeBill = new frm_ReportIncomeBill(maPhieuThu))
                                {
                                    rptIncomeBill.ShowDialog();
                                    ResetForm();
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Không tìm thấy thông tin người nộp tiền");
                    }
                }
                else
                {
                    MessageBox.Show("Cần phải nhập Họ tên người nộp tiền");
                }
            }
            else
            {
                if (UpdPhieuThu(SoPhieuThu, mucDichThu, soTien, lyDoNop))
                {
                    using (frm_ReportIncomeBill rptIncomeBill = new frm_ReportIncomeBill(SoPhieuThu))
                    {
                        rptIncomeBill.ShowDialog();
                        ResetForm();
                    }
                }
            }
        }

        private void radTextBox_Ten_Leave(object sender, EventArgs e)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var result = (from p in db.tbl_SinhViens
                              where p.ID == GetIDSinhVien(radTextBox_Ho.Text.Trim(), radTextBox_Ten.Text.Trim(), "", "")
                              select p).FirstOrDefault();
                if (result != null)
                {
                    radTextBox_MaSinhVien.Text = result.MaSinhVien;
                    radMaskedEditBox_SoCMND.Text = result.SoCMND;
                }
            }
        }

        private void radButton_Luu_Click(object sender, EventArgs e)
        {
            DateTime ngayThu = radDateTimePicker_NgayThu.Value;
            byte mucDichThu = Convert.ToByte(radDropDownList_MucDichThu.SelectedValue);
            byte kyThang = Convert.ToByte(radDropDownList_KyThang.Text);
            string ho = radTextBox_Ho.Text.Trim();
            string ten = radTextBox_Ten.Text.Trim();
            string hoTen = string.Format("{0} {1}", ho, ten);
            string maSinhVien = radTextBox_MaSinhVien.Text.Trim();
            string soCMND = radMaskedEditBox_SoCMND.Value.ToString();
            string diaChi = radTextBox_DiaChi.Text.Trim();
            string lyDoNop = radTextBox_LyDoNop.Text.Trim();
            decimal soTien = Convert.ToDecimal(radMaskedEditBox_SoTien.Value);
            int idSinhVien = GetIDSinhVien(ho, ten, maSinhVien, soCMND);
            string nam = radMaskedEditBox_Nam.Value.ToString();

            if (!update)
            {
                if (!string.IsNullOrEmpty(ho) && !string.IsNullOrEmpty(ten))
                {
                    if (idSinhVien > 0)
                    {
                        using (var db = new QuanLyKTXDataContext())
                        {
                            var result = (from p in db.tbl_SinhViens
                                          where p.ID == idSinhVien
                                          select p).FirstOrDefault();
                            maSinhVien = result.MaSinhVien;
                            soCMND = result.SoCMND;
                        }
                        bool flag = InsPhieuThu(ngayThu, mucDichThu, kyThang, nam, idSinhVien, hoTen, maSinhVien, soCMND, diaChi, lyDoNop, soTien);
                        if (flag)
                            ResetForm();
                    }
                    else
                    {
                        MessageBox.Show("Không tìm thấy thông tin người nộp tiền");
                    }
                }
                else
                {
                    MessageBox.Show("Cần phải nhập Họ tên người nộp tiền");
                }
            }
            else
            {
                if(UpdPhieuThu(SoPhieuThu, mucDichThu, soTien, lyDoNop)) BindGridPhieuThu();              
            }
        }

        private void radDropDownList_KyThang_Leave(object sender, EventArgs e)
        {
            ((Telerik.WinControls.UI.RadDropDownListEditableAreaElement)(radDropDownList_KyThang.GetChildAt(0).GetChildAt(0))).BackColor = Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
        }

        private void radDropDownList_KyThang_Enter(object sender, EventArgs e)
        {
            ((Telerik.WinControls.UI.RadDropDownListEditableAreaElement)(radDropDownList_KyThang.GetChildAt(0).GetChildAt(0))).BackColor = Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(253)))), ((int)(((byte)(215)))));
        }

        private void radDropDownList_MucDichThu_Leave(object sender, EventArgs e)
        {
            ((Telerik.WinControls.UI.RadDropDownListEditableAreaElement)(radDropDownList_MucDichThu.GetChildAt(0).GetChildAt(0))).BackColor = Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
        }

        private void radDropDownList_MucDichThu_Enter(object sender, EventArgs e)
        {
            ((Telerik.WinControls.UI.RadDropDownListEditableAreaElement)(radDropDownList_MucDichThu.GetChildAt(0).GetChildAt(0))).BackColor = Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(253)))), ((int)(((byte)(215)))));
        }

        private void frm_IncomeBill_Load(object sender, EventArgs e)
        {
            InitLoadForm();            
        }

        public frm_IncomeBill()
        {
            InitializeComponent();
            InitContextMenu();
        }

        #endregion
        
    }
}
